package com.suxin.netty.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;
import java.util.stream.IntStream;

/**
 * @author Tang
 * @classname MyChannelInboundHandler
 * @description [  ]
 * @date 2021/7/17 11:31
 */
public class MyChannelInboundHandler extends ChannelInboundHandlerAdapter {

    private Integer count = 0;

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("向客户端发送数据...开始");
        IntStream.range(1, 5).forEach(item -> {
            String str = "hello 我是server:" + (++count);
            ByteBuf buffer = Unpooled.buffer();
            buffer.writeBytes("header".getBytes());
            buffer.writeInt(str.getBytes().length);
            buffer.writeBytes("xxxx".getBytes());
            buffer.writeBytes(str.getBytes());
            ctx.writeAndFlush(buffer);
        });
        System.out.println("向客户端发送数据...结束");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf bb = (ByteBuf) msg;
        System.out.println("server读取到的内容为:" + (bb.toString(Charset.defaultCharset())));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("读取完成...");
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    }
}